<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\KsAppDspModel;
use app\model\KsNativeAuthModel;
use app\model\KsNativeVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\kuaishou\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class NativeVideoService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['native_video_list'];

    /**
     * 获取app.
     *
     * @param string $advertiserId 客户id
     */
    public static function getNativeVideo(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $nativeAuthModel = KsNativeAuthModel::where('advertiser_id', $advertiserId)->select()->toArray();
            foreach ($nativeAuthModel as $val) {
                foreach (KuaiShouEnum::CAMPAIGN_TYPE as $k => $value) {
                    $pcursor = '';
                    while (true) {
                        $result = self::getList($advertiserId, intval($val['user_id']), intval($val['kol_user_type']), $k, $pcursor);
                        if ($result === false) {
                            return false;
                        }
                        if ($pcursor == 'no_more') {
                            break;
                        }
                        $pcursor = $result['data']['pcursor'];
                        if (count($result['data']['photos']) == 0) {
                            break;
                        }
                        foreach ($result['data']['photos'] as $item) {
                            $model = self::getInfo($advertiserId, strval($item['photo_id']), intval($val['user_id']), $k);
                            if (! $model instanceof KsNativeVideoModel || ! $model->getKey()) {
                                $model = new KsNativeVideoModel();
                            }
                            $item['account_id'] = $obj->getKey();
                            $item['advertiser_id'] = $advertiserId;
                            $item['author_id'] = $val['user_id'];
                            $item['campaign_type'] = $k;
                            $item['cover_url'] = json_encode($item['cover_url']);
                            $item['movie_url'] = json_encode($item['movie_url']);
                            $model->setAttrs($item);
                            if (! $model->save()) {
                                throw new \Exception('保存NativeAuth出错');
                            }
                        }
                    }
                }
            }

            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取app信息.
     *
     * @param string $advertiserId 账户id
     * @param mixed $campaignType
     * @return null|array|KsAppDspModel|mixed|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', string $photoId = '', int $authorId = 0, $campaignType = 0)
    {
        $where = [
            ['author_id', '=', $authorId],
            ['photo_id', '=', $photoId],
            ['advertiser_id', '=', $advertiserId],
            ['campaign_type', '=', $campaignType],
        ];
        return (new KsNativeVideoModel())->where($where)->field(true)->find();
    }

    /**
     * 获取应用列表.
     *
     * @param string $advertiserId 账户id
     * @param mixed $kolUsertype 原生达人类型
     * @param mixed $campaignType 计划类型
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $authorId = 0, int $kolUsertype = 0, int $campaignType = 0, string $pcursor = '')
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'author_id' => $authorId,
            'kol_user_type' => $kolUsertype,
            'campaign_type' => $campaignType,
            'count' => KuaiShouEnum::MAX_NUMBER,
            'pcursor' => $pcursor,
        ];
        return AdvertiserService::getNativeVideoList($headers, $params);
    }
}
